import React, { useState } from 'react';
import { Form, Input, Select, Switch, Button, Space, Card, Typography, InputNumber } from 'antd';
import { FlowPath, FlowPathFormValues, FlowPathStatus, FlowPathNodeType } from './store/flowpathTypes';
import VariableForm from './components/VariableForm';
import NodeEditor from './components/NodeEditor';
import EdgeEditor from './components/EdgeEditor';

const { TextArea } = Input;
const { Title } = Typography;

interface FlowPathFormProps {
  initialValues?: FlowPath;
  onSubmit: (values: FlowPathFormValues) => void;
  onCancel: () => void;
}

const FlowPathForm: React.FC<FlowPathFormProps> = ({ initialValues, onSubmit, onCancel }) => {
  const [form] = Form.useForm();
  const [nodes, setNodes] = useState<FlowPathFormValues['nodes']>(initialValues?.nodes || []);
  const [edges, setEdges] = useState<FlowPathFormValues['edges']>(initialValues?.edges || []);
  const [variables, setVariables] = useState<FlowPathFormValues['variables']>(initialValues?.variables || []);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      onSubmit({
        ...values,
        nodes,
        edges,
        variables,
      });
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      initialValues={initialValues}
      onFinish={handleSubmit}
    >
      {/* 基本信息卡片 */}
      <Card title="基本信息" style={{ marginBottom: 16 }}>
        <Form.Item
          name="name"
          label="工作流名称"
          rules={[
            { required: true, message: '请输入工作流名称' },
            { max: 50, message: '工作流名称不能超过50个字符' }
          ]}
        >
          <Input placeholder="请输入工作流名称" />
        </Form.Item>

        <Form.Item
          name="description"
          label="工作流描述"
          rules={[{ max: 500, message: '描述不能超过500个字符' }]}
        >
          <TextArea rows={4} placeholder="请输入工作流描述" />
        </Form.Item>

        <Form.Item
          name="version"
          label="版本号"
          rules={[
            { required: true, message: '请输入版本号' },
            { pattern: /^[0-9]+\.[0-9]+\.[0-9]+$/, message: '版本号格式不正确，如：1.0.0' }
          ]}
        >
          <Input placeholder="请输入版本号" />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            {Object.values(FlowPathStatus).map(status => (
              <Select.Option key={status} value={status}>
                {status}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Card>

      {/* 变量定义卡片 */}
      <Card title="变量定义" style={{ marginBottom: 16 }}>
        <VariableForm
          variables={variables}
          onChange={setVariables}
        />
      </Card>

      {/* 节点编辑卡片 */}
      <Card title="节点编辑" style={{ marginBottom: 16 }}>
        <NodeEditor
          nodes={nodes}
          edges={edges}
          onChange={(newNodes, newEdges) => {
            setNodes(newNodes);
            setEdges(newEdges);
          }}
        />
      </Card>

      {/* 高级设置卡片 */}
      <Card title="高级设置" style={{ marginBottom: 16 }}>
        <Form.Item
          name="tags"
          label="标签"
        >
          <Select
            mode="tags"
            style={{ width: '100%' }}
            placeholder="请输入标签"
          />
        </Form.Item>

        <Form.Item
          name="modelIds"
          label="可用的模型"
        >
          <Select
            mode="multiple"
            style={{ width: '100%' }}
            placeholder="请选择可用的模型"
          />
        </Form.Item>

        <Form.Item
          name="functionIds"
          label="可用的函数"
        >
          <Select
            mode="multiple"
            style={{ width: '100%' }}
            placeholder="请选择可用的函数"
          />
        </Form.Item>

        <Form.Item
          name="apiIds"
          label="可用的API"
        >
          <Select
            mode="multiple"
            style={{ width: '100%' }}
            placeholder="请选择可用的API"
          />
        </Form.Item>

        <Form.Item
          name="isPublic"
          label="是否公开"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Form.Item
          name="isEnabled"
          label="是否启用"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Form.Item
          name="timeout"
          label="超时时间（毫秒）"
          rules={[
            { type: 'number', min: 1000, message: '超时时间必须大于1000毫秒' }
          ]}
        >
          <InputNumber min={1000} step={1000} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="retryTimes"
          label="重试次数"
          rules={[
            { type: 'number', min: 0, max: 5, message: '重试次数必须在0到5之间' }
          ]}
        >
          <InputNumber min={0} max={5} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="retryInterval"
          label="重试间隔（毫秒）"
          rules={[
            { type: 'number', min: 1000, message: '重试间隔必须大于1000毫秒' }
          ]}
        >
          <InputNumber min={1000} step={1000} style={{ width: '100%' }} />
        </Form.Item>
      </Card>

      {/* 表单按钮 */}
      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button onClick={onCancel}>
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default FlowPathForm;